package com.endbd.systemmanagement.service.user;

import com.endbd.feignapi.model.system.User;
import com.endbd.systemmanagement.dao.user.UserDao;
import com.endbd.systemmanagement.model.PageUsers;
import com.endbd.systemmanagement.model.UserCondition;
import com.endbd.systemmanagement.model.UserInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

  @Autowired
  private UserDao userDao;

  @Override
  public PageUsers<UserInfo> queryUserByCondition(UserCondition userCondition,int page, int size) {
    PageHelper.startPage(page,size);
    List<UserInfo> list = userDao.queryUsersByPage(userCondition);
    PageInfo<UserInfo> pageInfo=new PageInfo<>(list);
    PageUsers<UserInfo> users = new PageUsers<>();
    users.setPage(pageInfo.getPageNum());
    users.setSize(pageInfo.getPageSize());
    users.setTotalPage(pageInfo.getPages());
    users.setTotalSize((int)pageInfo.getTotal());
    users.setList(list);
    return users;
  }

  @Transactional(rollbackFor = {Exception.class})
  public int create(User user) {
    int k=userDao.queryUId(user.getUId());
    if(k>0) return 2;
    user.setStatusId(1);
    user.setHireDate(new Date());
    int i= userDao.createUser(user);
    return i;
  }

  @Override
  public boolean updateUser(User user) {
    Integer statusId = user.getStatusId();
    if(statusId==0) user.setLeaveDate(new Date());
    return userDao.updateUser(user)==1;
  }
}
